package com.cosina.game.robodefence.core;

import android.graphics.Point;

import com.cosina.game.robodefence.model.Enemy;
import com.cosina.game.robodefence.model.Way;

public abstract class BattleField{

	static final Point size = new Point(20, 12);

	protected final int[][] data = new int[size.y][size.x];

	public BattleField() {
		for (int y = 0; y < data.length; y++) {
			for (int x = 0; x < data[0].length; x++) {
				if (y == 0 || y == 11 || x == 0 || x == 19) {
					data[y][x] = -1;
				}
			}
		}

	}

	public final int[][] getFieldData() {
		return data;
	}

	private final boolean checkDefeaultWayCanBuilder(int x, int y) {
		if (data[y][x] != 0) {
			return false;
		} else {
			data[y][x] = 1;

			boolean cango = true;

			for (Way eachWay : getWay()) {
				if (eachWay.isBlock()) {
					cango = false;
					break;
				}
			}
			data[y][x] = 0;
			return cango;
		}
		
	}
	
	
	public final boolean checkCanBuilder(int x, int y){
		if(checkDefeaultWayCanBuilder(x,y)){
			for(Enemy enemey : BattleEngine.enemyManager.enemies){
				if(enemey.way.canBuild(x, y)== false){
					return false;
				}
			}
			return true;
		}else{
			return false;
		}
		
	}

	public final boolean canBuilder4Way(int x, int y, Way way) {
		data[y][x] = 1;

		boolean cango = true;

		if (way.isBlock()) {
			cango = false;
		}
		data[y][x] = 0;
		return cango;
	}

	public abstract Way[] getWay();

	public final void build(int x, int y, int kind) {
		this.data[y][x] = kind;
		for (Way each : getWay()) {
			each.updateIfCross(x, y);
		}
		BattleEngine.enemyManager.updateEnemyWayWhenBuild(x, y);
	}
	
	public final void demolition(int x, int y){
		this.data[y][x] = 0;
		for (Way each : getWay()) {
			each.update();
		}
		BattleEngine.enemyManager.updateEnemyWayWhenDemolition();
	}

	public void buildUp(int x, int y, int kind) {
		this.data[y][x] = kind;
	}
}
